﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyBlog.Common;
using MyBlog.Service;
using System.Security.Claims;
using System.Text;
using MyBlog.IService;
using Autofac;
using SqlSugar;
using MyBlog.Model.Entity;
using Common.Model;
using MyBlog.Model.ViewModels;
using AutoMapper;

namespace MyBlog.Controllers
{
    public class BlogController : Controller
    {
        private IMapper _mapper;
        private readonly IBlogService _blogService;
        private readonly IBlogTypeService _BlogTypeService;
        private readonly IUserBlogService _userBlogService;
        private readonly IUserService _userService;
        private readonly IUserBlogInfoService _userBlogInfoService;
        public BlogController(IComponentContext componentContext, IMapper mapper)
        {
            _blogService = componentContext.Resolve<IBlogService>();
            _BlogTypeService = componentContext.Resolve<IBlogTypeService>();
            _userBlogService = componentContext.Resolve<IUserBlogService>();
            _userService = componentContext.Resolve<IUserService>();
            _userBlogInfoService = componentContext.Resolve<IUserBlogInfoService>();
            _mapper= mapper;
        }

        [HttpGet]
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> Create()
        {
            List<BlogType> blogtypes =await _BlogTypeService.QueryAsync();
            BlogViewModel model = new BlogViewModel()
            {
                BlogTypes = blogtypes
            };
            return View(model);
        }
        /// <summary>
        /// 新建博客
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> Create(BlogViewModel model)
        {
            ApiDataResult<Blog> apiResult = new ApiDataResult<Blog>();
            DateTime dateTime = Convert.ToDateTime(DateTime.Now.ToString("G"));
            var blog= _mapper.Map<Blog>(model);
            blog.Id = Guid.NewGuid().ToString();
            blog.CreateTime= dateTime;
            blog.UpdateTime = dateTime;
            try
            {
                //long blogId = await  _blogService.AddAndReturnIdAsync(blog);
                if (!(await _blogService.AddAsync(blog)))
                    //if (blogId==0)
                {
                    apiResult.Success = false;
                    apiResult.Message = "发布失败";
                    return Json(apiResult);
                }
                string id = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value;
                UserBlog userBlog = new UserBlog()
                {
                    BlogId = blog.Id,
                    UserId = Convert.ToInt32(id)
                };
                if (!await _userBlogService.AddAsync(userBlog))
                {
                    apiResult.Success = false;
                    apiResult.Message = "发布失败";
                    return Json(apiResult);
                }
                //修改用户博客信息表中的博客总数
                var userBlogInfo = await _userBlogInfoService.FindAsync(Convert.ToInt32(id));
                if (userBlogInfo == null)
                {
                    userBlogInfo = new UserBlogInfo()
                    {
                        UserId = Convert.ToInt32(id),
                    };
                    await _userBlogInfoService.AddAsync(userBlogInfo);
                }
                userBlogInfo.BlogCount++;
                await _userBlogInfoService.ModifyAsync(userBlogInfo);

            }
            catch (Exception ex)
            {
                apiResult.Success = false;
                apiResult.Message = "发布失败:"+ex.Message;
                return Json(apiResult);
            }
           

            apiResult.Success = true;
            apiResult.Message = "发布成功";
            apiResult.Data = blog;
            return Json(apiResult);
        }

        [HttpGet]
        public  IActionResult PublishFinish(string id)
        {
            ViewBag.BlogId = id;
            return View();
        }

        public async Task<IActionResult> Detail(string id) {
            var blog= (await _blogService.QueryAsync(b=>b.Id==id)).FirstOrDefault();
            if (blog == null)
            {
                throw new Exception($"没有查询到Id为{id}的博客");
            }
            string blogTypeName = "";
            try
            {

                if (blog.BlogTypeId != 0)
                {
                    var blogType = await _BlogTypeService.FindAsync(blog.BlogTypeId);
                    blogTypeName = blogType.Name;
                }
                var list = await _userBlogService.QueryAsync(ub => ub.BlogId == blog.Id);
                UserBlog userBlog = list.FirstOrDefault();
                int userId = userBlog.UserId;
                string userName =(await _userService.FindAsync(userId)).Name;

                UserBlogViewModel model = new UserBlogViewModel()
                {
                    Title = blog.Title,
                    Content = blog.Content,
                    UpdateTime = blog.UpdateTime,
                    Photo = blog.Photo,
                    Views = blog.Views,
                    BlogType = blogTypeName,
                    UserId = userId,
                    UserName = userName,
                };
                //修改博客浏览量
                blog.Views++;
                await _blogService.ModifyAsync(blog);
                //var aa = _userBlogInfoService.GetAll();
                //var userBlogInfo = aa.FirstOrDefault(u => u.Id == userId);
                //修改用户博客信息表中的总浏览量

                var userBlogInfo = await _userBlogInfoService.FindAsync(userId);
                userBlogInfo.PageView++;
                await _userBlogInfoService.ModifyAsync(userBlogInfo);
                return View(model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        [HttpPost]
        public async Task<IActionResult> AllList(int page)
        {
            RefAsync<int> sum = new RefAsync<int>();
                List<Blog> blogs = (await _blogService.QueryOrderbyTime(x=>x.BlogTypeId!=0,page, 10, sum,false)).OrderByDescending(b=>b.CreateTime).ToList();
                List<string> datas = new List<string>();
                string data = await GetHtmlData(blogs);
            datas.Add(data);
            PagingData<string> pagingData = new PagingData<string>()
            {
                DataList = datas,
                PageIndex = page,
                PageSize = 10,
                RecordCount = sum/10+1
            };

            ApiDataResult<PagingData<string>> apiDataResult = new ApiDataResult<PagingData<string>>()
            {
                Success = true,
                Message = "查询成功",
                Data = pagingData

            };
                return new JsonResult(apiDataResult);

        }

        /// <summary>
        /// 获取所有博客
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="blogType">博客类型(1:所有2:CSharp;3:C++;4:Java;5:Sql)</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetBlogs(int page,int blogType=0)
        {
            RefAsync<int> sum = new RefAsync<int>();
            List<Blog> blogs = (await _blogService.QueryOrderbyTime(x => x.BlogTypeId != 0, page, 10, sum, false)).OrderByDescending(b => b.CreateTime).ToList();
            if(blogType == 0)
            {
                blogs = (await _blogService.QueryOrderbyTime(x => x.BlogTypeId != 0, page, 10, sum, false)).OrderByDescending(b => b.CreateTime).ToList();
            }
            else
            {
                blogs = (await _blogService.QueryOrderbyTime(x => x.BlogTypeId == blogType, page, 10, sum, false)).OrderByDescending(b => b.CreateTime).ToList();
            }

            List<string> datas = new List<string>();
            string data = await GetHtmlData(blogs);
            datas.Add(data);
            PagingData<string> pagingData = new PagingData<string>()
            {
                DataList = datas,
                PageIndex = page,
                PageSize = 10,
                RecordCount = sum / 10 + 1
            };

            ApiDataResult<PagingData<string>> apiDataResult = new ApiDataResult<PagingData<string>>()
            {
                Success = true,
                Message = "查询成功",
                Data = pagingData

            };
            return new JsonResult(apiDataResult);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="blogs"></param>
        /// <param name="userBlogs"></param>
        /// <param name="id">用户Id</param>
        /// <returns></returns>
        private async Task<string> GetHtmlData(List<Blog> blogs, int id=0)
        {
            StringBuilder stringBuilder = new StringBuilder();
            User user = null;
            foreach (var blog in blogs)
            {
                var list= await _userBlogService.QueryAsync(ub => ub.BlogId == blog.Id);
                UserBlog userBlog = list.FirstOrDefault();
                if (userBlog == null) continue;
                int userId = userBlog.UserId;
                user =await _userService.FindAsync(userId);
                string Introduction = blog.Introduction!= null ? blog.Introduction : blog.Title;
                string type= (await _BlogTypeService.FindAsync(blog.BlogTypeId)).Name;

                stringBuilder.Append("<div style='padding: 16px;margin:10px;background-color:#f7f7f7' >");
                stringBuilder.Append("<div class='layui-row layui-col-space15'>");
                stringBuilder.Append("<div class='layui-col-md2' style=''>");
                stringBuilder.Append($" <img   src='/images/Cover/{blog.Photo}' style='height:130px;width:150px'/>");
                stringBuilder.Append("</div>");
                stringBuilder.Append("<div class='layui-col-md10' style='line-height:1.5'>");
                stringBuilder.Append($"<a  href='/Blog/Detail/{blog.Id}' class='layui-font-18'  style='font-weight:bold'>{blog.Title}</a> <br />");
                stringBuilder.Append($"<label class='layui-font-16' style='width:1072px;height:70px'>{Introduction}</label><br />");
                if(id==0)
                    stringBuilder.Append($"作者：<a style='margin-right:10px' href='/User/Index/{userId}' class='layui-font-16'>{user.Name}</a>");
                stringBuilder.Append($"<label style='margin-right:10px' class='layui-font-16 layui-icon layui-icon-eye'>{blog.Views}</label>");
                stringBuilder.Append($"<label style='margin-right:10px' class='layui-font-16 layui-icon layui-icon-time'>{blog.UpdateTime}</label>"); 
                stringBuilder.Append($"类别：<label style='margin-right:10px' class='layui-font-16 layui-icon layui-icon-tree'>{type}</label>");
                stringBuilder.Append("</div>");
                stringBuilder.Append("</div>");
                stringBuilder.Append("</div><hr style='margin:10px'>");

                //stringBuilder.Append(html);
            }
            return stringBuilder.ToString();
        }
    }
}
